import Vue from 'vue'
import cookies from "@/libs/util.cookies"
import util from "@/libs/util.date"
// 数组删除方法
Array.prototype.remove = function (val) {
  var index = this.indexOf(val)
  if (index > -1) {
    this.splice(index, 1)
  }
}
// 判断数组中是否包含某个字符串
export const include = (val, arr) => {
  for (let i = 0; i < arr.length; i++) {
    if (val === arr[i]) {initToken
      return true
    }
  }
  return false
}

// 节流函数
export const throttle = (fn, delay = 100) => {
  let timer = null
  return data => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn()
    }, delay)
  }
}

// requestAnimationFrame 动画
export const requestAnimationFrame = window.requestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  function (callback) {
    window.setTimeout(callback, 1000 / 60)
  }
export const cancelRequestAnimationFrame = window.cancelAnimationFrame || clearTimeout

export const scrollLeft = (el, from = 0, to, duration = 500, endCallback) => {
  let difference = Math.abs(from - to) // 滚动距离
  let step = Math.ceil(difference / duration * 50) // 步长

  function scroll(start, end, step) {
    if (start === end) {
      endCallback && endCallback()
      return
    }
    // 每次绘制动画时更新起始距离
    let d = (start + step > end) ? end : start + step
    if (start > end) {
      d = (start - step < end) ? end : start - step
    }
    if (el === window) {
      window.scrollTo(d, d)
    } else {
      el.scrollLeft = d
    }
    // requestAnimationFrame实现最优性能动画绘制
    window.requestAnimationFrame(() => scroll(d, end, step))
  }
  scroll(from, to, step)
}

// 类型判断函数
export const getType = v => Object.prototype.toString.call(v)

export const isArray = v => getType(v) === '[object Array]'

export const isString = v => getType(v) === '[object String]'

export const isObject = v => getType(v) === '[object Object]'

export const isFunction = v => getType(v) === '[object Function]'

// 拷贝函数
export const merge = (...rest) => {
  let target = rest[0] || {}
  let src
  let copy
  let clone
  let i = 1
  let deep = false
  if (typeof target === 'boolean') {
    deep = target
    target = rest[1] || {}
    i++
  }
  for (; i < rest.length; i++) {
    let option = rest[i]
    for (let name in option) {
      src = target[name]
      copy = option[name]
      if (deep && copy && typeof copy === 'object') {
        if (isArray(copy)) {
          clone = src && isArray(src) ? src : []
        } else {
          clone = src && isObject(src) ? src : {}
        }
        target[name] = merge(clone, copy)
      } else if (copy !== undefined) {
        target[name] = copy
      }
    }
  }
  return target
}
// 找到目标组件向下(子组件)的所有相关组件名的组件
export const findComponentsDownward = (context, componentName) => {
  return context.$children.reduce((components, child) => {
    if (child.$options.name === componentName) {
      components.push(child)
    }
    let foundChilds = findComponentsDownward(child, componentName)
    return components.concat(foundChilds)
  }, [])
}
// 找到目标组件向上(父组件)的所有相关组件名的组件
export const findComponentsUpward = (context, componentName) => {
  let parents = []
  const parent = context.$parent
  if (parent) {
    if (parent.$options.name === componentName) {
      parents.push(parent)
    }
    return parents.concat(findComponentsUpward(parent, componentName))
  } else {
    return []
  }
}
// 找到目标组件上层的第一个相关组件名的父组件
export const findComponentUpward = (context, componentName) => {
  let componentNames
  if (typeof componentName === 'string') {
    componentNames = [componentName]
  } else {
    componentNames = componentName
  }

  let parent = context.$parent
  let name = parent.$options.name // 父组件的组件名
  while (parent && (!name || componentNames.indexOf(name) < 0)) {
    parent = parent.$parent
    if (parent) {
      name = parent.$options.name
    }
  }
  return parent
}
// 找到目标组件下层的第一层相关组件名的子组件
export const findOneLayerComponentsDownward = (context, componentName) => {
  return context.$children.reduce((components, child) => {
    if (child.$options.name === componentName) {
      components.push(child)
    }
    return components
  }, [])
}
// 检测是否有该class
export const hasClass = (el, cls) => {
  if (!el || !cls) {
    return false
  }
  if (cls.indexOf(' ') !== -1) {
    throw new Error('className should not contain space.')
  }
  if (el.classList) {
    return el.classList.contains(cls)
  } else {
    return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1
  }
}
// 移除class
export const removeClass = (el, cls) => {
  if (!el || !cls) {
    return
  }
  const classes = cls.split(' ')
  let curClass = ' ' + el.className + ' '

  for (let i = 0, j = classes.length; i < j; i++) {
    const clsName = classes[i]
    if (!clsName) {
      continue
    }

    if (el.classList) {
      el.classList.remove(clsName)
    } else if (hasClass(el, clsName)) {
      curClass = curClass.replace(' ' + clsName + ' ', ' ')
    }
  }
  if (!el.classList) {
    el.className = (curClass || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '')
  }
}
// 添加class
export const addClass = (el, cls) => {
  if (!el) {
    return
  }
  let curClass = el.className
  const classes = (cls || '').split(' ')

  for (let i = 0, j = classes.length; i < j; i++) {
    const clsName = classes[i]
    if (!clsName) {
      continue
    }

    if (el.classList) {
      el.classList.add(clsName)
    } else if (!hasClass(el, clsName)) {
      curClass += ' ' + clsName
    }
  }
  if (!el.classList) {
    el.className = curClass
  }
}

// 添加事件
export const setEvent = (dom, event, fn) => {
  dom.addEventListener(event, fn)
}

// 去除事件
export const offEvent = (dom, event, fn) => {
  dom.removeEventListener(event, fn)
}

// scrollTop 动画
export const scrollTop = (el, from = 0, to, duration = 500, endCallback) => {
  let difference = Math.abs(from - to) // 滚动距离
  let step = Math.ceil(difference / duration * 50) // 步长

  function scroll(start, end, step) {
    if (start === end) {
      endCallback && endCallback()
      return
    }
    // 每次绘制动画时更新起始距离
    let d = (start + step > end) ? end : start + step
    if (start > end) {
      d = (start - step < end) ? end : start - step
    }
    if (el === window) {
      window.scrollTo(d, d)
    } else {
      if (!el) {
        let anchor = document.querySelector('.web-index')
        anchor.scrollTop = d
      } else {
        el.scrollTop = d
      }
    }
    // requestAnimationFrame实现最优性能动画绘制
    window.requestAnimationFrame(() => scroll(d, end, step))
  }
  scroll(from, to, step)
}

// 获取style样式值
export const getStyleComputedProperty = (dom, property) => {
  let css
  if (dom.currentStyle) { // IE兼容
    css = dom.currentStyle
  } else { // firefox 和 chrome的兼容
    css = window.getComputedStyle(dom, null)
  }
  return css[property]
}
// 判断浏览器版本
export const browser = () => {
  var userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
  var isOpera = userAgent.indexOf('Opera') > -1 // 判断是否Opera浏览器
  var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera // 判断是否IE浏览器
  var isEdge = userAgent.indexOf('Edge') > -1 // 判断是否IE的Edge浏览器
  var isFF = userAgent.indexOf('Firefox') > -1 // 判断是否Firefox浏览器
  var isSafari = userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') == -1 // 判断是否Safari浏览器
  var isChrome = userAgent.indexOf('Chrome') > -1 && userAgent.indexOf('Safari') > -1 // 判断Chrome浏览器

  if (isIE) {
    var reIE = new RegExp('MSIE (\\d+\\.\\d+);')
    reIE.test(userAgent)
    var fIEVersion = parseFloat(RegExp['$1'])
    if (fIEVersion == 7) {
      return 'IE7'
    } else if (fIEVersion == 8) {
      return 'IE8'
    } else if (fIEVersion == 9) {
      return 'IE9'
    } else if (fIEVersion == 10) {
      return 'IE10'
    } else {
      return '0'
    }
    // IE版本过低
  } // isIE end

  if (isEdge) {
    return 'Edge'
  }
  if (isFF) {
    return 'FF'
  }
  if (isOpera) {
    return 'Opera'
  }
  if (isSafari) {
    return 'Safari'
  }
  if (isChrome) {
    return 'Chrome'
  }
} // myBrowser() end

export const dateInterval = (beginDate, endDate, type) => {
  let dateList = [];
  // beginDate = beginDate.replace(/-| |:/g, "")
  // endDate = endDate.replace(/-| |:/g, "")
  beginDate = beginDate.replace(/-/g, "")
  beginDate = beginDate.replace(/ /g, "")
  beginDate = beginDate.replace(/:/g, "")
  endDate = endDate.replace(/-/g, "")
  endDate = endDate.replace(/ /g, "")
  endDate = endDate.replace(/:/g, "")

  if (type == 'year') {
    for (beginDate; beginDate <= endDate; beginDate++) {
      dateList.push(String(beginDate))
    }
  } else if (type == 'month') {
    for (Number(beginDate); Number(beginDate) <= Number(endDate);) {
      dateList.push(String(beginDate))
      let year = beginDate.substring(0, 4)
      let month = beginDate.substring(4)
      if (Number(month) < 12) {
        let m = Number(month) + 1;
        if (m < 10) {
          m = '0' + m
        }
        beginDate = year + m
      } else if (month == 12) {
        beginDate = (Number(year) + 1) + '01'
      }
    }
  } else if (type == 'date') {
    for (beginDate; beginDate <= endDate;) {
      dateList.push(beginDate)
      let year = beginDate.substring(0, 4)
      let month = beginDate.substring(4, 6)
      let day = beginDate.substring(6)
      let mDays = new Date(year, month, 0).getDate()

      if (day < mDays) {
        let d = Number(day) + 1;
        if (d < 10) {
          d = '0' + d
        }
        beginDate = year + month + d
      } else if (day == mDays) {
        if (month < 12) {
          let m = Number(month) + 1;
          if (m < 10) {
            m = '0' + m
          }
          beginDate = year + m + '01'
        } else if (month == 12) {
          beginDate = (Number(year) + 1) + '01' + '01'
        }
      }
    }
  } else if (type == 'datetime') {
    let reset = (date) => {
      let year = date.substring(0, 4)
      let month = date.substring(4, 6)
      let day = date.substring(6, 8)
      let hours = date.substring(8, 10)
      let minutes = date.substring(10)
      let mDays = new Date(year, month, 0).getDate()

      if (minutes == "00") {
      } else if (Number(minutes) <= 15) {
        date = Number(date.substring(0, 10) + "15")
      } else if (Number(minutes) <= 30) {
        date = Number(date.substring(0, 10) + "30")
      } else if (Number(minutes) <= 45) {
        date = Number(date.substring(0, 10) + "45")
      } else if (Number(minutes) <= 59) {
        if (Number(hours) < 23) {
          let h = Number(hours) + 1;
          if (h < 10) {
            h = '0' + hours
          }
          date = date.substring(0, 8) + h + "00"
        } else {
          if (day < mDays) {
            let d = Number(day) + 1;
            if (d < 10) {
              d = '0' + d
            }
            date = year + month + d + "0000"
          } else {
            if (month < 12) {
              let m = Number(month) + 1;
              if (m < 10) {
                m = '0' + m
              }
              date = year + m + '01' + "0000"
            } else {
              date = (Number(year) + 1) + '01' + '01' + "0000"
            }
          }
        }
      }

      return date
    }


    beginDate = reset(beginDate)
    endDate = reset(endDate)

    // console.log(beginDate, endDate)

    for (beginDate; beginDate <= endDate;) {
      // console.log(beginDate)
      beginDate = String(beginDate)
      endDate = String(endDate)
      dateList.push(beginDate)

      let year = beginDate.substring(0, 4)
      let month = beginDate.substring(4, 6)
      let day = beginDate.substring(6, 8)
      let hours = beginDate.substring(8, 10)
      let minutes = beginDate.substring(10)
      let mDays = new Date(year, month, 0).getDate()

      if (minutes == "00") {
        beginDate = Number(beginDate.substring(0, 10) + "15")
      } else if (Number(minutes) < 15) {
        beginDate = Number(beginDate.substring(0, 10) + "15")
      } else if (Number(minutes) < 30) {
        beginDate = Number(beginDate.substring(0, 10) + "30")
      } else if (Number(minutes) < 45) {
        beginDate = Number(beginDate.substring(0, 10) + "45")
      } else if (Number(minutes) < 59) {
        if (Number(hours) < 23) {
          let hour = Number(hours) + 1;
          if (hour < 10) {
            hour = '0' + hour
          }
          beginDate = beginDate.substring(0, 8) + hour + "00"
        } else {
          if (day < mDays) {
            let d = Number(day) + 1;
            if (d < 10) {
              d = '0' + d
            }
            beginDate = year + month + d + "0000"
          } else {
            if (month < 12) {
              let m = Number(month) + 1;
              if (m < 10) {
                m = '0' + m
              }
              beginDate = year + m + '01' + "0000"
            } else {
              beginDate = (Number(year) + 1) + '01' + '01' + "0000"
            }
          }
        }
      }
    }
  }

  dateList = dateList.map(item => {
    if (type == 'month') {
      item = item.substring(0, 4) + "-" + item.substring(4)
    } else if (type == "date") {
      item = item.substring(0, 4) + "-" + item.substring(4, 6) + "-" + item.substring(6)
    } else if (type == "datetime") {
      item = item.substring(0, 4) + "-" + item.substring(4, 6) + "-" + item.substring(6, 8) + " " + item.substring(8, 10) + ":" + item.substring(10)
    }
    return item;
  })

  return dateList;
}

// 当前日期
export const getNowFormatDate = (val) => {
  let date = new Date()
  let seperator = '-'
  if (val === 'year') {
    return date.getFullYear() + ''
  } else if (val === 'month') {
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    let currentdate = year + seperator + month
    return currentdate
  } else if (val === 'date') {
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let strDate = date.getDate()
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    let currentdate = year + seperator + month + seperator + strDate
    return currentdate
  }
}
// 格式化日期
export const formatDate = (val, type) => {
  let date = val
  let seperator = '-'
  if (type === 'year') {
    return date.getFullYear() + ''
  } else if (val === 'month') {
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    let currentdate = year + seperator + month
    return currentdate
  } else if (type === 'date') {
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let strDate = date.getDate()
    if (month >= 1 && month <= 9) {
      month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate
    }
    let currentdate = year + seperator + month + seperator + strDate
    return currentdate
  }
}

/* eslint-disable */
if (!Date.prototype.format) {
  // eslint-disable-next-line no-extend-native
  Date.prototype.format = function (mask) {
    var d = this
    var zeroize = function (value, length) {
      if (!length) length = 2
      value = String(value)
      for (var i = 0, zeros = ''; i < (length - value.length); i++) {
        zeros += '0'
      }
      return zeros + value
    }

    return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0) {
      switch ($0) {
        case 'd':
          return d.getDate();
        case 'dd':
          return zeroize(d.getDate());
        case 'ddd':
          return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
        case 'dddd':
          return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
        case 'M':
          return d.getMonth() + 1;
        case 'MM':
          return zeroize(d.getMonth() + 1);
        case 'MMM':
          return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
        case 'MMMM':
          return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
        case 'yy':
          return String(d.getFullYear()).substr(2);
        case 'yyyy':
          return d.getFullYear();
        case 'h':
          return d.getHours() % 12 || 12;
        case 'hh':
          return zeroize(d.getHours() % 12 || 12);
        case 'H':
          return d.getHours();
        case 'HH':
          return zeroize(d.getHours());
        case 'm':
          return d.getMinutes();
        case 'mm':
          return zeroize(d.getMinutes());
        case 's':
          return d.getSeconds();
        case 'ss':
          return zeroize(d.getSeconds());
        case 'l':
          return zeroize(d.getMilliseconds(), 3);
        case 'L':
          var m = d.getMilliseconds();
          if (m > 99) m = Math.round(m / 10);
          return zeroize(m);
        case 'tt':
          return d.getHours() < 12 ? 'am' : 'pm';
        case 'TT':
          return d.getHours() < 12 ? 'AM' : 'PM';
        case 'Z':
          return d.toUTCString().match(/[A-Z]+$/);
        // Return quoted strings with the surrounding quotes removed
        default:
          return $0.substr(1, $0.length - 2);
      }
    });
  }
}
/* eslint-enable */

// 比较日期大小
export const compareDate = (date1, date2) => {
  let date11 = new Date(date1)
  let date22 = new Date(date2)
  if (date11.getTime() > date22.getTime()) {
    return true
  } else {
    return false
  }
}
// 数字 日期 相减
export const shortDate = (date1, date2) => {
  let date11 = ''
  let date22 = ''
  let isTime = false
  if (isNaN(+date1)) {
    date11 = isNaN(new Date(date1)) ? new Date('1 ' + date1) : new Date(date1)
    date22 = isNaN(new Date(date2)) ? new Date('1 ' + date2) : new Date(date2)
    return date22.getTime() / 1000 - date11.getTime() / 1000
  } else {
    date11 = +date1
    date22 = +date2
    return date22 - date11
  }
}
export const formCheck = (val, that) => {
  let msg = []
  val.map(data => {
    if (that[data]) {
      if (typeof (that[data]) === 'string') {
        if (that.$refs[data].$el) {
          that.$refs[data].$el.classList.remove('must')
        } else {
          that.$refs[data].classList.remove('must')
        }
      } else if (Array.isArray(that[data])) {
        if (that[data].length) {
          if (typeof (that[data][0]) === 'string') {
            that.$refs[data].$el.classList.remove('must')
          } else {
            that[data].map((iteam, index) => {
              Object.keys(iteam).map((item, ind) => {
                if (that[data][index][item]) {
                  if (Array.isArray(that.$refs[data + item + index])) {
                    that.$refs[data + item + index][0].$el.classList.remove('must')
                  } else {
                    that.$refs[data + item + index].$el.classList.remove('must')
                  }
                } else {
                  if (Array.isArray(that.$refs[data + item + index])) {
                    that.$refs[data + item + index][0].$el.classList.add('must')
                    msg.push(that.$refs[data + item + index][0].$el.children[0].innerHTML)
                  } else {
                    that.$refs[data + item + index].$el.classList.add('must')
                    msg.push(that.$refs[data + item + index].$el.children[0].innerHTML)
                  }
                }
              })
            })
          }
        }
      } else {
        Object.keys(that[data]).map((iteam, index) => {
          if (that[data][iteam]) {
            that.$refs[data].$el.children[index].classList.remove('must')
          } else {
            that.$refs[data].$el.children[index].classList.add(' must ')
            msg.push(that.$refs[data].$el.children[index].children[0].innerHTML)
          }
        })
      }
    } else {
      if (that.$refs[data].$el) {
        that.$refs[data].$el.classList.add('must')
        msg.push(that.$refs[data].$el.children[0].innerHTML)
      } else {
        that.$refs[data].classList.add('must')
        msg.push(that.$refs[data].children[0].innerHTML)
      }
    }
  })
  if (msg.length > 0) {
    that.$Modal.info({
      title: '提示',
      content: msg.join() + ' 的内容不能为空!'
    })
    return false
  }
  return true
}

export const ifNull = (val, that) => {
  let msg = []
  val.map(data => {
    if (that.$refs[data].currentValue == '' || that.$refs[data].currentValue == 'null' || that.$refs[data].currentValue == null) {
      that.$refs[data].$el.children[1].classList.add('nullInput')
      msg.push(that.$refs[data].name)
    } else {
      that.$refs[data].$el.children[2].classList.remove('nullInput')
    }
  })
  if (msg.length > 0) {
    that.$Modal.info({
      title: '提示',
      content: msg.join() + ' 的内容不能为空!'
    })
    return false
  } else {
    return true
  }
}

export const isNull = (arr, that) => {
  let msg = []
  arr.map(data => {
    if (data.value === '' || data.value === 'null' || data.value === null || data.value === undefined) {
      msg.push(data.title)
    }
    if (data.value instanceof Array) {
      if (data.value.length === 0) {
        msg.push(data.title)
      }
    }
  })
  if (msg.length > 0) {
    that.$Modal.info({
      title: '提示',
      content: '[ ' + msg.join(' 、') + ' ] 该项是必填项'
    })
    return false
  } else {
    return true
  }
}

class _BASE64 {
  constructor() {
    this._keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  }
  encode(input) {
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4
    var output = ''
    var i = 0
    input = this._utf8_encode(input)
    while (i < input.length) {
      chr1 = input.charCodeAt(i++)
      chr2 = input.charCodeAt(i++)
      chr3 = input.charCodeAt(i++)
      enc1 = chr1 >> 2
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
      enc4 = chr3 & 63
      if (isNaN(chr2)) {
        enc3 = enc4 = 64
      } else if (isNaN(chr3)) {
        enc4 = 64
      }
      output = output +
        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4)
    }
    return output
  }
  decode(input) {
    var output = ''
    var chr1, chr2, chr3
    var enc1, enc2, enc3, enc4
    var i = 0
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '')
    while (i < input.length) {
      enc1 = this._keyStr.indexOf(input.charAt(i++))
      enc2 = this._keyStr.indexOf(input.charAt(i++))
      enc3 = this._keyStr.indexOf(input.charAt(i++))
      enc4 = this._keyStr.indexOf(input.charAt(i++))
      chr1 = (enc1 << 2) | (enc2 >> 4)
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)
      chr3 = ((enc3 & 3) << 6) | enc4
      output = output + String.fromCharCode(chr1)
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2)
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3)
      }
    }
    output = this._utf8_decode(output)
    return output
  }
  _utf8_encode(string) {
    string = string.replace(/\r\n/g, '\n')
    var utftext = ''
    for (var n = 0; n < string.length; n++) {
      var c = string.charCodeAt(n)
      if (c < 128) {
        utftext += String.fromCharCode(c)
      } else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192)
        utftext += String.fromCharCode((c & 63) | 128)
      } else {
        utftext += String.fromCharCode((c >> 12) | 224)
        utftext += String.fromCharCode(((c >> 6) & 63) | 128)
        utftext += String.fromCharCode((c & 63) | 128)
      }
    }
    return utftext
  }
  _utf8_decode(utftext) {
    var string = ''
    var i = 0
    var c, c1, c2, c3
    c = c1 = c2 = 0
    while (i < utftext.length) {
      c = utftext.charCodeAt(i)
      if (c < 128) {
        string += String.fromCharCode(c)
        i++
      } else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1)
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63))
        i += 2
      } else {
        c2 = utftext.charCodeAt(i + 1)
        c3 = utftext.charCodeAt(i + 2)
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))
        i += 3
      }
    }
    return string
  }
}
export const BASE64 = new _BASE64()

export const initToken = () => {
  let tokenStr = cookies.get('access_token')
  if (!tokenStr || tokenStr == '-1') { return false }
  let userMessage = BASE64.decode(tokenStr.split('.')[1]).replace(
    /\'|\"|\{|\}/g,
    ''
  )
  let userMessageJson = {}
  let itemArr = userMessage.split(',')
  let initObjArr = []
  itemArr.map(item => {
    initObjArr.push(item.split(':'))
  })
  initObjArr.map(item => {
    userMessageJson[item[0]] = item[1]
  })
  return userMessageJson
}

export const iniTabList = (list = [], router, fn) => {
  // 获取cookie
  let pageTabList = cookies.get('pageTabList')
  // 初始化页面标签数组
  list =
    pageTabList !== 'undefined' && !!pageTabList
      ? JSON.parse(pageTabList) : []
  // 初始化标签项
  const pushPageList = (list, route) => {
    list.push({
      tabText: route.meta.title,
      tabName: route.name,
      active: false
    })
  }
  if (list.length > 0) {
    let me = this
    let canPush = false
    for (var i = 0, len = list.length; i < len; i++) {
      if (list[i].tabName === undefined) { return false }
      if (list[i].tabName.indexOf(router.name) === -1) {
        canPush = true
      } else {
        canPush = false
        break
      }
    }
    canPush && pushPageList(list, router)
    list.map(item => {
      item.active = item.tabName == router.name
    })
  } else {
    pushPageList(list, router)
    list[0].active = true
  }
  // 设置获取cookie
  cookies.set('pageTabList', JSON.stringify(list))
  return isFunction(fn) ? fn(list) : list
}

// 合并对象，相同属性的值相加
export const mergeTogether = () => {
  let temp = []

  obj.forEach(function (item, index) {
    let skey = item.date + item.state

    if (typeof temp[skey] === 'undefined') {
      temp[skey] = item
    } else {
      for (let k in item.result) {
        temp[skey]['result'][k] += item['result'][k]
      }
    }
  })
  let result = []
  for (let i in temp) {
    result.push(temp[i])
  }
}

// 判断闰月
export const getCountDays = ym => {
  let curDate = new Date(ym)
  /* 获取当前月份 */
  let curMonth = curDate.getMonth()
  /* 生成实际的月份: 由于curMonth会比实际月份小1, 故需加1 */
  curDate.setMonth(curMonth + 1)
  /* 将日期设置为0 */
  curDate.setDate(0)
  /* 返回当月的天数 */
  return curDate.getDate()
}

/**
 * 处理echarts数据
 * @param {*} option
 * 源数据集 => []
 * @param {*} params
 * 参数集 =>
 * {
 *  x: 以此属性为 x 轴坐标 ,
 *  filter: 以此属性为过滤条件 ,
 *  valid: 取此属性的值组成数组
 * }
 */

// 处理时间集合
const returnAutoX = (dateObj) => {
  if (isObject(dateObj)) {
    let { type, tagDate, interval = 1 } = dateObj
    switch (type) {
      case 'minus':
        let minLen = 1440 / interval
        let hour = 0
        let minute = 0
        let change = 60 / interval
        let minuArr = ['00:00']
        for (var i = 1; i < minLen; i++) {
          if (!(i % change)) {
            hour++
            minute = 0
          } else {
            minute += interval
          }
          minuArr.push((hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute))
        }
        return minuArr
      case 'hours':
        let hourArr = []
        let hLen = 24 / interval
        for (var i = 0; i < hLen; i++) {
          let currentHour = i * interval
          hourArr[i] = (currentHour < 10 ? '0' + currentHour : '' + currentHour) + ':00'
        }
        return hourArr
      case 'days':
        let newMonth = tagDate.split('-')[1]
        let days = getCountDays(tagDate)
        let dLen = days / interval
        let dayArr = []
        for (var i = 0; i < dLen; i++) {
          let currentDay = i * interval + 1
          dayArr[i] = newMonth + '-' + (currentDay < 10 ? '0' + currentDay : '' + currentDay)
        }
        return dayArr
      case 'months':
        let monthArr = []
        let monLen = 12 / interval
        for (var i = 0; i < monLen; i++) {
          let currentMonth = i * interval + 1
          monthArr[i] = currentMonth < 10 ? '0' + currentMonth : '' + currentMonth
        }
        return monthArr
      case 'years':
        return []
    }
    return []
  }
}
export const returnEchartData = (option = [], params = {}) => {
  if (!isArray(option) || option.length < 0) { return {} }
  params = isObject(params) ? params : false
  const { x, autoX, y, filter, valid } = params
  let keys = isObject(option[0]) ? Object.keys(option[0]) : []
  if (!isArray(keys) || keys.length < 0) { return false }
  let datas = {}
  let addMonth = ''
  let isMonth = isObject(autoX) && autoX.type == 'days'
  if (isMonth) {
    !autoX.tagDate && (autoX.tagDate = util.getNowFormatDate('month'))
    addMonth = autoX.tagDate.split('-')[1]
  }
  option.map((item, index) => {
    keys.map(key => {
      if (!isArray(datas[key])) {
        datas[key] = []
      }
      let xVal = (isMonth && item[x].length == 2) ? addMonth + '-' + item[x] : item[x]
      datas[key][index] = !x && !y ? item[key] : (key == x || key == y) ? item[key] : !y ? [xVal, (item[key] == 'null' || item[key] == null) ? 0 : item[key]] : [item[y], xVal, (item[key] == 'null' || item[key] == null) ? 0 : item[key]]
    })
  })
  if (!filter) {
    !!x && (datas[x] = returnAutoX(autoX) || datas[x])
    return datas
  } else if (x) {
    let filters = {}
    let filtersNames = []
    datas[filter].map((item, index) => {
      filtersNames[index] = item.length == 3 ? item[2] : item[1]
    })
    filtersNames = Array.from(new Set(filtersNames))
    filtersNames.map((item, index) => {
      filters['datas' + index] = { values: [], name: item }
    })
    option.map(item => {
      for (let key in item) {
        let flag = !valid ? (key != filter && key != x && key != y) : key == valid
        if (flag) {
          let addMonth = ''
          let isMonth = isObject(autoX) && autoX.type == 'days'
          if (isMonth) {
            !autoX.tagDate && (autoX.tagDate = util.getNowFormatDate('month'))
            addMonth = autoX.tagDate.split('-')[1]
          }
          let xVal = (isMonth && item[x].length == 2) ? addMonth + '-' + item[x] : item[x]
          if (!!item[filter]) {
            filters['datas' + filtersNames.indexOf(item[filter])].values.push(!y ? [xVal, (item[key] == 'null' || item[key] == null) ? 0 : item[key]] : [item[y], xVal, (item[key] == 'null' || item[key] == null) ? 0 : item[key]])
          }
        }
      }
    })
    filters[x] = Array.from(new Set(datas[x]))
    filters[x] = returnAutoX(autoX) || filters[x]
    !!y && (filters[y] = Array.from(new Set(datas[y])))
    console.log(filters,"filters")
    return filters
  } else {
    return {}
  }
}

// resize
/**
 * Created by taozh on 2017/5/6.
 * taozh1982@gmail.com
 */
export const EleResize = {
  _handleResize: function (e) {
    var ele = e.target || e.srcElement;
    var trigger = ele.__resizeTrigger__;
    if (trigger) {
      var handlers = trigger.__z_resizeListeners;
      if (handlers) {
        var size = handlers.length;
        for (var i = 0; i < size; i++) {
          var h = handlers[i];
          var handler = h.handler;
          var context = h.context;
          handler.apply(context, [e]);
        }
      }
    }
  },
  _removeHandler: function (ele, handler, context) {
    var handlers = ele.__z_resizeListeners;
    if (handlers) {
      var size = handlers.length;
      for (var i = 0; i < size; i++) {
        var h = handlers[i];
        if (h.handler === handler && h.context === context) {
          handlers.splice(i, 1);
          return;
        }
      }
    }
  },
  _createResizeTrigger: function (ele) {
    var obj = document.createElement('object');
    obj.setAttribute('style',
      'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden;opacity: 0; pointer-events: none; z-index: -1;');
    obj.onload = EleResize._handleObjectLoad;
    obj.type = 'text/html';
    ele.appendChild(obj);
    obj.data = 'about:blank';
    return obj;
  },
  _handleObjectLoad: function (evt) {
    this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__;
    this.contentDocument.defaultView.addEventListener('resize', EleResize._handleResize);
  }
};
if (document.attachEvent) {//ie9-10
  EleResize.on = function (ele, handler, context) {
    var handlers = ele.__z_resizeListeners;
    if (!handlers) {
      handlers = [];
      ele.__z_resizeListeners = handlers;
      ele.__resizeTrigger__ = ele;
      ele.attachEvent('onresize', EleResize._handleResize);
    }
    handlers.push({
      handler: handler,
      context: context
    });
  };
  EleResize.off = function (ele, handler, context) {
    var handlers = ele.__z_resizeListeners;
    if (handlers) {
      EleResize._removeHandler(ele, handler, context);
      if (handlers.length === 0) {
        ele.detachEvent('onresize', EleResize._handleResize);
        delete ele.__z_resizeListeners;
      }
    }
  }
} else {
  EleResize.on = function (ele, handler, context) {
    var handlers = ele.__z_resizeListeners;
    if (!handlers) {
      handlers = [];
      ele.__z_resizeListeners = handlers;

      if (getComputedStyle(ele, null).position === 'static') {
        ele.style.position = 'relative';
      }
      var obj = EleResize._createResizeTrigger(ele);
      ele.__resizeTrigger__ = obj;
      obj.__resizeElement__ = ele;
    }
    handlers.push({
      handler: handler,
      context: context
    });
  };
  EleResize.off = function (ele, handler, context) {
    var handlers = ele.__z_resizeListeners;
    if (handlers) {
      EleResize._removeHandler(ele, handler, context);
      if (handlers.length === 0) {
        var trigger = ele.__resizeTrigger__;
        if (trigger) {
          trigger.contentDocument.defaultView.removeEventListener('resize', EleResize._handleResize);
          ele.removeChild(trigger);
          delete ele.__resizeTrigger__;
        }
        delete ele.__z_resizeListeners;
      }
    }
  }
}
